import Service from "../modules/Service";
import Config from "../../Config";
import { token, language } from "../../util/storage";
import i18n from "../../lang/index";
import { debounce } from "lodash";
import MainErrorStatus from './MainErrorStatus';
import CommonErrorStatus from '../CommonErrorStatus';

export default class MainService {
  public service = new Service({
    baseUrl: new Config().MAIN_BASE_API,
    header: {}
  });

  private commonErrorStatus = new CommonErrorStatus();

  private errorStatus = new MainErrorStatus();

  constructor() {
    console.log("process.env.MAIN_BASE_API: ", JSON.stringify(process as any));
    this.service.interceptors.request((config) => {
      // Add X-Access-Token header to every request, you can add other custom headers here
      if (token.get()) {
        (config.header as any)["X-Access-Token"] = token.get();
        (config.header as any).Authorization = token.get();
        (config.header as any)["Content-Type"] = (config.header as any)["Content-Type"] || "application/json;charset=UTF-8";
        (config.header as any)["Accept-Language"] = language.get() === "zh" ? "zh-Hans" : "en-US"; // 让每个请求携带中英文标志
      }
      return config;
    }, (error) => {
      uni.showToast({
        title: i18n.t("common.service_error_status.default").toString(),
        duration: 2000,
        icon: "none"
      });
      return Promise.reject(error);
    });
    
    this.service.interceptors.response((response) => {
      console.log(response);
      const res = response.data;
      if (!/[2][0-9]*/.test(res.status_code.toString())) {
        if ((this.errorStatus as any)[res.status_code.toString()]) {
          (this.errorStatus as any)[res.status_code.toString()]();
        }
      } else {
        return response.data;
      }
    }, (error) => {
      if (error.response) {
        if (error.response.status && (this.commonErrorStatus as any)[error.response.status.toString()]) {
          (this.commonErrorStatus as any)[error.response.status.toString()](error.response);
        } else {
          this.commonErrorStatus.default();
        }
      }
      return Promise.reject(error);
    })
  }
}
